<template>
  <div class="carry">
    <v-navbar></v-navbar>
    <div class="carry-wrapper">
      <div>
        <head-icon :className="className" :price="price" :text="text"></head-icon>
        <div class="recharge">
          <div class="wrapper">
            <div class="recharge-way">
              <div class="way-item" :class="{'select': select === 1}" @click="selectCheck(1)">
                <i class="icon zfb"></i>
                <span class="text">支付宝</span>
              </div>
              <!--<div class="way-item" :class="{'select': select === 2}" @click="selectCheck(2)">-->
              <!--<i class="icon wx"></i>-->
              <!--<span class="text">微信支付</span>-->
              <!--</div>-->
              <div class="way-item" :class="{'select': select === 0}" @click="selectCheck(0)">
                <i class="icon r-card"></i>
                <span class="text">银行卡</span>
              </div>
            </div>
            <!--<ul class="recharge-prices">-->
            <!--<li class="price-item" v-for="(v, i) in priceArr" :key="i" @click="e_selectMoney(v)">-->
            <!--<input type="radio" ref="radio" :id="radioId[i]" name="selectRadio" :disabled='selectSelf'/>-->
            <!--<label :for="radioId[i]"></label>-->
            <!--&lt;!&ndash; <img :src="v" width="74" heigzht="35" alt=""> &ndash;&gt;-->
            <!--<div class="rechargeBack">-->
            <!--<span v-text="`￥${v}`" />-->
            <!--</div>-->
            <!--</li>-->
            <!--</ul>-->
            <div class="info">
              <div class="zfb-info" v-if="select === 1">
                <div class="infos">
                  <span>收款人支付宝：{{zfbNum}}</span>
                </div>
              </div>
              <div class="bank-info" v-else>
                <div class="infos">
                  <span>收款人姓名：{{bankCardUserName}}</span>
                  <span>银行卡号：{{bankCardNumber}}</span>
                  <span>所属银行：{{affiliatedBank}}</span>
                  <span>开户行：{{subordinateBranch}}</span>
                </div>
              </div>
            </div>
            <div class="other">
              <icon-title :iconClass="burseIcon" :text="burseInfo"></icon-title>
              <div class="other-text">
                <div class="o-content">
                  <span class="name">充值金额</span>
                  <!--<span class="cue">(充值金额为100的整数倍)</span>-->
                </div>
                <input type="number" v-model="rechargeAmount" class="inpt-price" placeholder="￥0.00">
              </div>
              <div class="other-text">
                <div class="o-content">
                  <span class="name">支付类型</span>
                </div>
                <div class="other-item">
                  <input type="radio" ref="radio" v-model="payType" value="1" id="zfb" name="selectTyle"/>
                  <label for="zfb"></label>
                  <span>支付宝</span>
                </div>
                <!-- <div class="other-item">
                  <input type="radio" ref="radio" v-model="payType" value="2" id="wx" name="selectTyle"/>
                  <label for="wx"></label>
                  <span>微信</span>
                </div> -->
                <div class="other-item">
                  <input type="radio" ref="radio" v-model="payType" value="0" id="bank" name="selectTyle"/>
                  <label for="bank"></label>
                  <span>银行卡</span>
                </div>
              </div>
              <div class="other-text">
                <div class="o-content">
                  <span class="name">支付号码</span>
                </div>
                <input type="number" v-model="payNum" class="inpt-price" placeholder="请输入支付号码">
              </div>
            </div>
            <div @click="e_pay">
              <v-button :text="btnText"></v-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import navbar from '@c/navbar/navbar'
  import headIcon from '@c/headIcon/headIcon'
  import assets from '@c/assets/assets'
  import iconTitle from '@c/iconTitle/iconTitle'
  import Button from '@c/button/button'
  import { mapState, mapMutations } from 'vuex'
  import img100 from '@imgs/recharge/100.png'
  import img200 from '@imgs/recharge/200.png'
  import img500 from '@imgs/recharge/500.png'
  import img1000 from '@imgs/recharge/1000.png'
  import img2000 from '@imgs/recharge/2000.png'
  import img3000 from '@imgs/recharge/3000.png'

  const ZFB = 1
  const WX = 2
  const CARD = 0
  import { vpost, sonpost, fpost, gpost, vlink } from '@api/axios'
  import { tokenPost, jtpost, gtpost, tokenLink, jtget } from '@api/axiosByToken'

  export default {
    name: 'Carry',
    data() {
      return {
        className: 'recharge',
        price: 0,
        text: '当前余额',
        select: ZFB, // 默认支付宝充值
        radioId: [], // 单选按钮关联id数组
        priceArr: [], //图片路径数组
        burseIcon: 'burse',
        burseInfo: '其它金额',
        btnText: '充值',
        selectSelf: false,
        selectMoney: '', //推荐金额
        rechargeAmount: '',
        zfbNum: '',//支付宝号
        bankCardUserName: '',//姓名
        bankCardNumber: '',//银行卡号
        affiliatedBank: '',//所属银行
        subordinateBranch: '',//开户行
        payNum: '',//支付号码
        payType: '1',//支付类型
      }
    },
    components: {
      'v-navbar': navbar,
      'head-icon': headIcon,
      'icon-title': iconTitle,
      'v-button': Button,
    },

    computed: {
      ...mapState(['wtitle', 'rback', 'signed']),
      radio(v) {
        let str = 'icon-' + v
        return str
      },
    },
    methods: {
      ...mapMutations(['WTITLE', 'RBACK', 'USERSINGED']),
      // ============================================获取推荐充值金额👇=============================================//
      getPopMoney() {
        tokenPost(tokenLink.recharge.getRechargeMoney, {}).then(re => {
          if (re.status == 0) {
            this.priceArr = re.data.listMoney
            this.price = re.data.remainingSum
          }
        })
      },
      e_selectMoney(v) {
        this.selectMoney = v
      },
      // ============================================获取推荐充值金额👆=============================================//
      // 判断选择支付宝还是选择微信
      selectCheck(val) {
        if (val === ZFB) {
          this.select = ZFB
          return
        } else if (val === WX) {
          this.select = WX
        } else {
          this.select = CARD
          return
        }
      },
      // 存储id数组
      _keepIdArr() {
        let arr = []
        for (let i = 0; i < this.priceArr.length; i++) {
          arr.push('img' + i)
        }
        return arr
      },
      // ============================================点击充值唤起支付👇========================================================//
      e_pay() {
        // this.doSubmit()
        this._doPayCheck()
      },
      /**
       * 充值前验证
       */
      _doPayCheck() {
        let num = ''
        if (this.select === 1) {
          num = this.zfbNum
        } else {
          num = this.bankCardNumber
        }
        let info = {
          userId: localStorage.getItem('userId'),
          type: this.payType,
          number: this.payNum,
          typeSk: this.select,
          numberSk: num,
          money: this.rechargeAmount,
        }

        if (info.money === '') {
          this.$Message.error('充值金额格式不对')
          return
        }

        if (info.money < 0) {
          this.$Message.error('充值金额格式不对')
          return
        }
        if (info.number === '') {
          this.$Message.error('支付号码不能为空')
          return
        }

        tokenPost(tokenLink.rechargeNew, info).then(re => {
          if (re.status === 0) {
            this.$Message.success('提交成功，请等待审核！')
            setTimeout(() => {
              this.$router.back(-1)
            }, 1000)
          } else {
            this.$Message.error(re.msg)
          }
        })
      },
      // 提交充值金额
      doSubmit() {
        let rechargeMoney = ''
        if (this.selectMoney) {
          rechargeMoney = this.selectMoney
        } else {
          rechargeMoney = this.rechargeAmount
        }
        let subdata = {
          userId: localStorage.getItem('userId'),
          money: rechargeMoney,
        }
        if (subdata.money == '') {
          this.$Message.warning('请选择或者输入要充值的金额')
          return
        }

        tokenPost(tokenLink.recharge.submitRecharge, subdata).then(re => {
          if (re.status == 0) {
            this.select == ZFB
              ? this.aliPay(re.data)
              : this.WeChatAppPay(re.data)
          }
        })
      },
      // ============================================点击充值唤起支付👆========================================================//

      // ============================================微信支付👇=======================================================//
      WeChatAppPay(orderID) {
        let getdata = {
          userId: localStorage.getItem('userId'),
          orderId: orderID,
        }
        tokenPost(tokenLink.recharge.subWithWeChat, getdata).then(re => {
          console.log(re)
          if (re.status == 0) {
            var params = {
              appId: re.data.appId,
              partnerid: re.data.partnerId, // merchant id
              prepayid: re.data.prepayId, // prepay id
              noncestr: re.data.nonceStr, // nonce
              timestamp: re.data.timeStamp, // timestamp
              sign: re.data.sign, // signed string
            }
            console.log(params)

            Wechat.sendPaymentRequest(
              params,
              function(response) {
                if (type == 'shopCar') {
                  //清空购物车
                  // self.shopCar.removeAll()
                }
                self.$router.push({
                  path: 'success',
                  query: {
                    id: orderId,
                    type: 'order',
                    time: new Date().getTime(),
                  },
                })
              },
              function(reason) {
                this.$router.push({
                  path: 'collectDetail',
                  query: {
                    id: orderId,
                    time: new Date().getTime(),
                  },
                })
              },
            )
          }
        })
      },
      // ============================================微信支付👆=======================================================//

      // ============================================支付宝支付👇====================================================//
      aliPay(orderID) {
        let paydata = {
          userId: localStorage.getItem('userId'),
          orderId: orderID,
        }
        tokenPost(tokenLink.recharge.alipay, paydata).then(res => {
          this.AliAppPay(res)
        })
      },
      AliAppPay(response) {
        console.log('支付宝支付', response.data)

        Alipay.pay(
          response.data,
          res => {
            console.log('支付完成?', res)
            //支付完成
            if (res.resultStatus == '9000') {
              //跳转到支付成功
              self.$router.push({
                path: '/success',
                query: {
                  id: orderId,
                  type: self.isApply,
                  time: new Date().getTime(),
                },
              })
            }
          },
          e => {
            console.log('支付失败?', e)
            if (e.resultStatus == '6001') {
              self.$router.replace({
                path: '/mine',
                query: {
                  time: new Date().getTime(),
                },
              })
            }
          },
        )
      },
      // ============================================支付宝支付👆====================================================//
      /**
       * 获得收款人信息
       * @private
       */
      _getPayerInfo() {
        tokenPost(tokenLink.payerInfo).then(re => {
          if (re.status === 0) {
            this.zfbNum = re.data.alipayNumber
            this.bankCardUserName = re.data.bankCardUserName
            this.bankCardNumber = re.data.bankCardNumber
            this.affiliatedBank = re.data.affiliatedBank
            this.subordinateBranch = re.data.subordinateBranch
          } else {
            this.$Message.error(re.msg)
          }
        })
      },
    },
    created() {
      this.radioId = this._keepIdArr()
      this.WTITLE('充值')
      this.RBACK(true)

      // 获取推荐金额
      this.getPopMoney()
      this._getPayerInfo()
    },
    watch: {
      select() {
        return this.select
      },
      selectMoney() {
        this.rechargeAmount = ''
      },
      rechargeAmount() {
        for (let i = 0; i < this.$refs.radio.length; i++) {
          this.$refs.radio[i].checked = false
        }
        this.selectMoney = ''
      },
    },
  }
</script>
